import { app, autoUpdater, dialog } from 'electron'
import { mac } from '../util'

const isMac = mac()
const server = 'https://sf-browser-release.bb2b2bb.com'
const platform = isMac ? 'osx_64' : 'win64'
const url = `${server}/update/flavor/beta/${platform}/${app.getVersion()}/stable`

export async function initUpdater() {
  // 开发环境不更新
  if (process.env.NODE_ENV == 'development') {
    return
  }
  // MAC环境暂时不更新
  if (isMac) {
    return
  }

  autoUpdater.setFeedURL({ url })
  autoUpdater.on('error', console.error)
  autoUpdater.on('update-downloaded', (_event, releaseNotes, releaseName) => {
    dialog.showMessageBox({
      type: 'info',
      title: '应用更新',
      message: process.platform === 'win32' ? releaseNotes : releaseName,
      detail: '一个新的版本已准备好，请重启更新',
      buttons: ['现在更新']
    }).then((returnValue) => {
      if (returnValue.response === 0) autoUpdater.quitAndInstall()
    })
  })
  setInterval(() => {
    autoUpdater.checkForUpdates()
  }, 60000)
}
